package com.yin.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class C {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                data3.printD();
            }
        }, "D").start();
    }
}

class Data3 {
    private static final String st = "执行了";
    private final Lock lock = new ReentrantLock();
    private int number = 1;  // 1->A 2->B 3->C

    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();
    private final Condition conditionD = lock.newCondition();

    public void printA() {
        try {
            lock.lock();
            while (number != 1) {
                conditionA.await();
            }
            System.out.println(Thread.currentThread().getName() + st);
            number = 2;
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        try {
            lock.lock();
            while (number != 2) {
                conditionB.await();
            }
            System.out.println(Thread.currentThread().getName() + st);
            number = 3;
            conditionC.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        try {
            lock.lock();
            while (number != 3) {
                conditionC.await();
            }
            System.out.println(Thread.currentThread().getName() + st);
            number = 4;
            conditionD.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printD() {
        try {
            lock.lock();
            while (number != 4) {
                conditionD.await();
            }
            System.out.println(Thread.currentThread().getName() + st);
            number = 1;
            conditionA.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}